package com.example.blog.controller;

import com.example.blog.Service.UserService;
import com.example.blog.enumcode.EnumCode;
import com.example.blog.model.Result;
import com.example.blog.model.UserInfo;
import com.example.blog.utils.JWTUtils;
import io.jsonwebtoken.lang.Assert;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    @RequestMapping("/login")
    public Result login(String userName, String password) {
        log.info("username:{},password:{}", userName, password);
        if(!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            return Result.failure(EnumCode.NULLRESOURCE.getCode(),"账号或密码不能为空");
        }
        UserInfo userInfo = userService.selectByName(userName);
        if(userInfo == null || userInfo.getId() == null) {
            return Result.failure("用户不存在");
        }
        if(!password.equals(userInfo.getPassword())) {
            return Result.failure("账号或密码错误");
        }
        Map<String, Object> claim = new HashMap<>();
        claim.put("id", userInfo.getId() );
        claim.put("username", userInfo.getUsername());

        String token = JWTUtils.generateToken(claim);
        return Result.success(token);
    }
    @RequestMapping("/getUserInfo")
    public UserInfo getUserInfo(HttpServletRequest request) {
        String userToken = request.getHeader("user_token");
        log.info("userToken:{}", userToken);
        Integer id = JWTUtils.getUserId(userToken);
        return userService.getUserInfoById(id);
    }
    @RequestMapping("getAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId) {
        Assert.notNull(blogId,"博客id为空");
        return userService.getAuthorInfoByBlogId(blogId);
    }

}
